<template>
  <view class="Mall4j container" :style="{height:isMap?'100vh':''}">
    <view v-if="!isMap" class="submit-order">
      <!-- <view class="bg">
        // <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/submit-bg.png" />
      </view>
       收货地址 -->
      <view v-if="selectDistributionWay" class="distribution-mode">
        <view class="item-box">
          <view :class="[isDistribution ? 'active' : '' , 'item']" @tap="changeDistribution(0)">{{ i18n.mailToHome }}</view>
          <view :class="[isDistribution ? '' : 'active' , 'item']" @tap="changeDistribution(1)">{{ i18n.pickStore }}</view>
        </view>
      </view>
      <!-- 邮寄到家 -->
      <view v-if="isDistribution" class="address-box">
        <view v-if="!userAddr || isEditAddr">
          <view class="tit">
            <view v-if="!addressList.length" class="text">{{ i18n.fillReceivingInformation }}</view>
            <view v-if="addressList.length" class="text">{{ i18n.historicalAddress }}</view>
            <view v-if="addressList.length" class="total" @tap="AddressListPop">{{ i18n.inTotal }}{{ addressList.length }}{{ i18n.itemGe }}</view>
          </view>
          <view class="add-box">
            <view class="add-item">
              <view class="text">{{ i18n.consignee }}</view>
              <input type="text" class="input" :value="receiver" :placeholder="i18n.consigneeTips" @input="onReceiverInput" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
            </view>
            <view class="add-item">
              <view class="text">{{ i18n.mobilePhone }}</view>
              <input type="text" class="input" :value="mobile" :placeholder="i18n.enterContactNumber" maxlength="11" @input="onMobileInput" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
            </view>
            <view class="add-item" @tap="translate">
              <view class="text">{{ i18n.yourRegion }}</view>
              <view class="area" @input="onMobileInput" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
                <view v-if="province" class="">{{ province + ' ' + city + ' ' + area }}</view>
                <view v-if="!province" class="placeholder-text">{{ i18n.selectProvinceCity }}</view>
                <view class="animation-element-wrapper" :animation="animation" :style="'visibility:' + (show ? 'visible':'hidden')" @tap.stop="hiddenFloatView">
                  <view class="animation-element" @tap.stop="nono">
                    <text class="right-bt" @tap.stop="hiddenFloatView">{{ i18n.confirm }}</text>
                    <view class="line" />
                    <picker-view indicator-style="height: 50rpx;" :value="value" @change="bindChange" @tap.stop="nono">
                      <!--省-->
                      <picker-view-column>
                        <view v-for="(item, index) in provArray" :key="index">{{ item.areaName }}</view>
                      </picker-view-column>
                      <!--地级市-->
                      <picker-view-column>
                        <view v-for="(item, index) in cityArray" :key="index">{{ item.areaName }}</view>
                      </picker-view-column>
                      <!--区县-->
                      <picker-view-column>
                        <view v-for="(item, index) in areaArray" :key="index">{{ item.areaName }}</view>
                      </picker-view-column>
                    </picker-view>
                  </view>
                </view>
              </view>
            </view>
            <view class="add-item">
              <view class="text">{{ i18n.detailedAddress }}</view>
              <input type="text" class="input" :value="addr" :placeholder="i18n.enteDetailedAddress" @input="onAddrInput" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
              <image class="addres-icon" src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/submit-address.png" @tap="selMap" />
            </view>
            <view class="add-item">
              <view class="btn" @tap="onSaveAddr">{{ i18n.saveAndUse }}</view>
            </view>
          </view>
        </view>
        <view v-if="userAddr && !isEditAddr" class="current-address">
          <view style=" display: flex;
  align-items: center;">
            <view class="c-locate">
              <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/locate-img.png" />
            </view>
            <view class="c-address">{{ userAddr.province }}{{ userAddr.city }}{{ userAddr.area }}{{ userAddr.addr }}</view>
          </view>

          <view class="c-user">{{ userAddr.receiver }} {{ userAddr.mobile }}</view>
          <view class="c-edit" @tap="toAddrListPage">
            <text class="arrow" />
          </view>
        </view>
        <view v-if="canChooseSameCity || !orderItems.length" class="choose-way" @tap="distributionPop">
          <view class="text">{{ i18n.deliveryMethod }}</view>
          <view class="go">{{ dvyType==1?i18n.expressDelivery:dvyType==4?i18n.sameDelivery:i18n.selectDeliveryMethod }}</view>
        </view>
      </view>
      <!-- /邮寄到家 -->

      <!-- 到店自提 -->
      <view v-if="!isDistribution" class="address-box">
        <view class="self-raising">
          <view class="tit">
            <view class="text">{{ i18n.pickup }}</view>
          </view>
          <view class="choose-store" @tap="goSelectStore">
            <!--            <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/submit-address.png" class="img" />-->
            <view v-if="selStationItem.province" class="text">{{ selStationItem.province }}{{ selStationItem.city }}{{ selStationItem.area }}{{ selStationItem.addr }}</view>
            <view v-if="!selStationItem.province" class="text gray">{{ i18n.selectPickUpAddress }}</view>
          </view>
        </view>
        <view class="raising-user">
          <view class="tit">
            <view v-if="false" class="text">{{ i18n.fillPersonInformation }}</view>
            <view class="text">{{ i18n.historicalPickPerson }}</view>
            <view v-if="stationUserInfo" class="total" @tap="raisingUserList">{{ i18n.inTotal+ ' ' }}{{ stationUserInfo?stationUserInfo.length:'0' }}{{ i18n.itemGe }}</view>
          </view>
          <view class="user-info">
            <input type="text" class="input" :disabled="disabled" :value="stationUserName" :placeholder="i18n.enterNamePerson" maxlength="15" @input="getConsigneeInt" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
          </view>
          <view :class="['item',errorTips ? 'error':'']">
            <view class="user-info">
              <input type="text" class="input" :disabled="disabled" :value="stationUserMobile" :placeholder="i18n.enterPhonePerson" maxlength="11" @input="getConMobileInt" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
            </view>
            <view v-if="errorTips==1" class="error-text"><text class="warning-icon">!</text>{{ i18n.phoneWarn }}</view>
          </view>
        </view>
        <view class="choose-way" @tap="raisingTimePop">
          <view class="text">{{ i18n.takeDeliveryTime }}</view>
          <view class="go">{{ timeContent?dateContent+' '+timeContent:i18n.choosePickUpTime }}</view>
        </view>
      </view>
      <!-- /到店自提 -->

      <!-- 商品详情 -->
      <view class="shop-item">
        <view class="prod-item">
          <block v-for="(prodDiscItem,index) in shopCartItemDiscounts" :key="index">
            <view :class="['prod-block', prodDiscItem.chooseDiscountItemDto && preSellStatus!=1?'discount':'']">
              <!-- 满减提示 -->
              <view v-if="prodDiscItem.chooseDiscountItemDto && prodDiscItem.chooseDiscountItemDto.discountId && preSellStatus!=1" class="discount-tips">
                <text class="text-block">{{ wxs.parseDiscount(prodDiscItem.chooseDiscountItemDto.discountRule,curLang) }}</text>
                <text class="text-list">{{ wxs.parseDiscountMsg(prodDiscItem.chooseDiscountItemDto.discountRule,prodDiscItem.chooseDiscountItemDto.needAmount,prodDiscItem.chooseDiscountItemDto.discount,curLang) }}</text>
                <text v-if="prodDiscItem.chooseDiscountItemDto.reduceAmount>0" class="text-list reduce-amount">{{ i18n.haveDiscount }}￥{{ wxs.parsePrice(prodDiscItem.chooseDiscountItemDto.reduceAmount)[0] }}.{{ wxs.parsePrice(prodDiscItem.chooseDiscountItemDto.reduceAmount)[1] }}</text>
              </view>

              <!-- 商品信息 -->
              <view class="item-box">
                <view v-for="(item, prodId) in prodDiscItem.shopCartItems" :key="prodId" class="item-cont">
                  <view class="prod-pic">
                    <image v-if="item.pic" :src="item.pic" />
                    <image v-else src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/def.png" mode="aspectFit" />
                  </view>
                  <view class="prod-info">
                    <view class="prodname">{{ item.prodName }}</view>
                    <view class="prod-info-cont">{{ item.skuName }}</view>
                    <view class="price-nums">
                      <view class="prodprice">
                        <text class="symbol" style="color: #ff6d13">￥</text>
                        <text class="big-num" style="color: #ff6d13">{{ wxs.parsePrice(item.price)[0] }}</text>
                        <text class="small-num" style="color: #ff6d13">.{{ wxs.parsePrice(item.price)[1] }}</text>
                      </view>
                      <view class="prodcount">×{{ item.prodCount }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </block>
        </view>
        <!-- 商品明细 -->

        <!-- 店铺优惠券和买家留言 -->
        <view class="msg-item">
          <!-- 配送费用 s -->
          <view v-if="dvyType==4" class="item" style="justify-content: space-between">
            <view class="item-tit">{{ i18n.startDeliveryFee }}：</view>
            <view class=" black">
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(this.startDeliveryFee)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(this.startDeliveryFee)[1] }}</text>
            </view>
          </view>
          <view class="item" style="justify-content: space-between">
            <view class="item-tit">{{ i18n.shippingCosts }}：</view>
            <view class=" black">
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(transfee)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(transfee)[1] }}</text>
            </view>
          </view>
          <!-- 配送费用 e -->
          <!-- 优惠券 s -->
          <!-- <view v-if="coupons.canUseCoupons" class="item coupon" @tap="showCouponPopup">
            <view class="text-box">
              <text class="text">{{ i18n.coupon }}：</text>
              <text v-if="coupons.canUseCoupons.length==0" class="number">{{ i18n.notAvailable }}</text>
              <text v-else class="number">{{ coupons.canUseCoupons.length? coupons.canUseCoupons.length: 0 }}&nbsp;{{ i18n.zhangAvailable }}</text>
            </view>
            <view v-if="couponReduce" class="amount">
              <text class="symbol">-￥</text>
              <text class="big-num">{{ wxs.parsePrice(couponReduce)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(couponReduce)[1] }}</text>
            </view>
          </view> -->
          <!-- 优惠券 e -->

          <!-- NFT兑换卡 s -->
          <view v-if="nftCoupon.unUseCount" class="item coupon" @tap="showNftCouponPopup">
            <view class="text-box">
              <text class="text">兑换卡：</text>
              <text class="number">{{ nftCoupon.unUseCount }}&nbsp;张可用</text>
            </view>
            <view class="amount">
              <block v-if="shopReduce">
                <text class="symbol">-￥</text>
                <text class="big-num">{{ wxs.parsePrice(shopReduce)[0] }}</text>
                <text class="small-num">.{{ wxs.parsePrice(shopReduce)[1] }}</text>
              </block>
            </view>
          </view>
          <!-- 优惠券 e -->

          <!-- 留言 s-->
          <view class="item">
            <view class="tit">{{ i18n.storeNotes }}：</view>
            <input class="input" maxlength="100" :placeholder="i18n.storeNotesTips" :value="remark" @input="onRemarkIpt">
          </view>
          <!-- 留言 e-->
          <!-- 发票 s-->
          <!-- <view class="item invoice">
            <view class="invoice-title">{{ i18n.invoice.onvoiceIssuance }}：</view>
            <view v-if="!invoiceDataFrom.invoiceType || invoiceDataFrom.invoiceType === 2" class="invoice-arrow" @tap="showInvoicePopup(1)">
              <view class="text-arrow">
                <view class="text">{{ i18n.invoice.noInvoice }}</view>
              </view>
            </view>
            <view v-else class="invoice-arrow" @tap="showInvoicePopup(1,invoiceDataFrom)">
              <view class="text-arrow"> -->
          <!-- <view class="text">本次不开具发票</view> -->
          <!-- <view class="text">{{ i18n.invoice.electronic }}({{ i18n.invoice.productDetails }}-{{ invoiceDataFrom.headerName || i18n.invoice.personal }})</view>
              </view>
            </view>
          </view> -->
          <!-- 发票 e-->
        </view>
        <!-- /店铺优惠券和买家留言 -->

        <!-- 不满足当前配送方式的商品 -->
        <view v-if="filterShopItems && filterShopItems.length > 0" class="useless">
          <view class="u-reason">{{ i18n.productsNotSupported + ' ' }}{{ ['',i18n.expressDelivery,i18n.pickStore,'',i18n.sameDelivery][dvyType] }}，{{ i18n.chooseAnotherDelivery }}</view>
          <scroll-view scroll-x="true" class="u-con">
            <view class="u-box">
              <view v-for="(item,index) in filterShopItems" :key="index" class="u-prods">
                <image :src="item.pic" />
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <view class="order-msg">
        <!-- 会员积分 -->
        <!-- <view v-if="maxUsableScore > 0 && preSellStatus!=1" class="item coupon">
          <view class="member-points">
            <view class="integral-wrap">
              <view class="integral-deduction">
                <text class="tit">{{ i18n.pointsDeduction }}： </text>
                <view v-if="isScorePay==1" class="integral-tips" @tap.stop="handleScorePop">
                  <text v-if="totalScoreAmount>0 && totalUsableScore>0" class="text">{{ scorePlaceholder }}</text>
                  <text v-else class="text">{{ i18n.enterPoints }}</text>
                  <image src="https://mall-1312577323.cos.ap-chengdu.myqcloud.com/mall/images/icon/revise.png" />
                </view>
                <view v-if="isScorePay==0" class="integral-tips"> {{ i18n.notUsePoints }}</view>
              </view>
            </view>
            <view class="integral-right-select">
              <label>
                <checkbox color="#FF6D13" value="isScorePay" :checked="isChecked" @tap="useMemberPoints" />
              </label>
            </view>
          </view>
        </view> -->
        <!-- 商品总额 -->
        <view class="item">
          <view class="item-tit">{{ i18n.comTotal }}：</view>
          <view class="price black">
            <text class="symbol">￥</text>
            <text class="big-num">{{ wxs.parsePrice(total)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(total)[1] }}</text>
          </view>
        </view>
        <!-- 等级免运费金额 -->
        <view v-if="freeTransfee" class="item">
          <view class="item-tit">{{ i18n.gradeFreeAmount }}：</view>
          <view class="price">
            <text class="symbol">-￥</text>
            <text class="big-num">{{ wxs.parsePrice(freeTransfee)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(freeTransfee)[1] }}</text>
          </view>
        </view>
        <!-- 运费 -->
        <view class="item">
          <view class="item-tit">{{ i18n.shipping }}：</view>
          <view class="price black">
            <text class="symbol">￥</text>
            <text class="big-num">{{ wxs.parsePrice(totalTransfee)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(totalTransfee)[1] }}</text>
          </view>
        </view>
        <!-- 等级折扣金额 -->
        <view v-if="totalLevelAmount" class="item">
          <view class="item-tit">{{ i18n.memberDiscountAmount }}：</view>
          <view class="price">
            <text class="symbol">-￥</text>
            <text class="big-num">{{ wxs.parsePrice(totalLevelAmount)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(totalLevelAmount)[1] }}</text>
          </view>
        </view>
        <!-- 店铺优惠 -->
        <view v-if="shopReduce" class="item">
          <view class="item-tit">优惠金额：</view>
          <view class="price">
            <text class="symbol">-￥</text>
            <text class="big-num">{{ wxs.parsePrice(shopReduce)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(shopReduce)[1] }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 腾讯地图组件 -->
    <view v-if="isMap" class="map">
      <view class="goOut" @click="isMapReturn">返回</view>
      <iframe id="mapPage" width="100%" height="100%" frameborder="0" :src="`https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=${key}&referer=myappp`" />
      <!-- end 腾讯地图组件 -->
    </view>

    <!-- 底部栏 -->
    <view v-if="tabbar && !isMap" class="submit-order-footer">
      <view class="sub-order">
        <view class="item-txt">{{ i18n.total }}：<view class="price">
            <text class="symbol">￥</text>
            <text class="big-num">{{ wxs.parsePrice(actualTotal)[0] }}</text>
            <text class="small-num">.{{ wxs.parsePrice(actualTotal)[1] }}</text>
          </view>
        </view>
      </view>
      <view class="footer-box" @tap="toPay">{{ i18n.submitOrders }}</view>
    </view>

    <!-- 选择优惠券弹窗 -->
    <!-- <view v-if="popupShow" class="popup-hide">
      <view class="popup-box box-radius">
        <view class="popup-tit box-radius">
          <text>{{ i18n.coupon }}</text>
          <text class="close" @tap="closePopup" />
        </view>
        <view class="coupon-tabs">
          <view :class="'coupon-tab ' + (couponSts==1?'on':'')" data-sts="1" @tap="changeCouponSts">{{ i18n.availableCoupons }}({{ coupons.canUseCoupons.length }})</view>
          <view :class="'coupon-tab ' + (couponSts==2?'on':'')" data-sts="2" @tap="changeCouponSts">{{ i18n.unavailableCoupons }}({{ coupons.unCanUseCoupons.length }})</view>
        </view>
        <view class="popup-cnt">
          <block v-for="(item, couponId) in coupons.canUseCoupons" :key="couponId">
            <block v-if="couponSts == 1">
              <coupon :key="couponId" :item="item" :order="true" :can-use="true" @checkCoupon="checkCoupon" />
            </block>
          </block>
          <block v-for="(item, couponId) in coupons.unCanUseCoupons" :key="couponId">
            <block v-if="couponSts == 2 && update">
              <coupon :item="item" :order="true" :can-use="false" />
            </block>
          </block>
          <view class="botm-empty" />
        </view>
        <view v-if="couponSts==1" class="coupon-ok">
          <text @tap="choosedCoupon">{{ i18n.confirm }}</text>
        </view>
      </view>
    </view> -->

    <!-- 选择nft兑换卡弹窗 -->
    <view v-if="nftPopupShow" class="popup-hide">
      <view class="popup-box box-radius">
        <view class="popup-tit box-radius">
          <text>兑换卡</text>
          <text class="close" @tap="closePopup" />
        </view>
        <view class="coupon-tabs">
          <view :class="'coupon-tab ' + (nftCouponSts==0?'on':'')" data-sts="0" @tap="changeNftCouponSts">可用兑换卡({{nftCoupon.unUseCount}})</view>
          <view :class="'coupon-tab ' + (nftCouponSts==1?'on':'')" data-sts="1" @tap="changeNftCouponSts">不可用兑换卡({{nftCoupon.useCount}})</view>
        </view>
        <view class="popup-cnt">
          <view class="cen_c" v-for="(item, couponId) in nftCoupons.canUseCoupons" :key="couponId">
            <view class="box_5 flex-col" v-if="nftCouponSts == 0">
              <view class="section_2 ">
              </view>
              <view class="section_3 flex-row">
                <view class="group_3 flex-col">
                  <text class="text_5 clamp_text">￥{{item.amount}}</text>
                  <text class="text_6 ">商品兑换卡</text>
                  <view class="group_4 flex-col"></view>
                </view>
                <view class="text-group_2 flex-col">
                  <text class="text_7 clamp_text">商品全场通用</text>
                  <text class="text_8 clamp_text"> </text>
                  <text class="text_9 clamp_text">{{ item.createTime }}</text>
                </view>
              </view>
              <view class="section_4 flex-col"></view>
              <view class="section_5 flex-col"></view>
              <view class="text_10">
                <view class="sel-btn">
                  <checkbox color="#eb2444" :data-couponid="item.couponId" :checked="item.choose" @tap="checkNftCoupon" />
                </view>
              </view>
            </view>
          </view>
          <!--
          <block v-for="(item, couponId) in nftCoupons.canUseCoupons" :key="couponId">
            <block v-if="nftCouponSts == 0">
              <view class="coupon-item">
                <view class="left">
                  <view class="num">￥<text class="coupon-price">{{item.amount}}</text></view>
                  <view class="coupon-condition">
                    全场通用
                  </view>
                </view>
                <view class="right">
                  <view class="c-des">
                    <text class="c-type">商品</text>全场通用
                  </view>
                  <view class="c-date">
                    <view class="c-data-info">
                      {{ item.createTime }}
                    </view>
                  </view>
                  <view class="sel-btn">
                    <checkbox color="#eb2444" :data-couponid="item.couponId" :checked="item.choose" @tap="checkNftCoupon" />
                  </view>
                </view>
              </view>
            </block>
          </block>  -->
          <view class="cen_c" v-for="(item, couponId) in nftCoupons.unCanUseCoupons" :key="couponId">
            <view class="box_5_de box_5 flex-col" v-if="nftCouponSts == 1 && update">
              <view class="section_2 ">
              </view>
              <view class="section_3 flex-row">
                <view class="group_3 flex-col">
                  <text class="text_5 clamp_text">￥{{item.amount}}</text>
                  <text class="text_6 ">商品兑换卡</text>
                  <view class="group_4 flex-col"></view>
                </view>
                <view class="text-group_2 flex-col">
                  <text class="text_7 clamp_text">商品全场通用</text>
                  <text class="text_8 clamp_text"> </text>
                  <text class="text_9 clamp_text">{{ item.createTime }}</text>
                </view>
              </view>
              <view class="section_4 flex-col"></view>
              <view class="section_5 flex-col"></view>
              <view class="text_10">

              </view>
            </view>
          </view>

          <!--

          <block v-for="(item, couponId) in nftCoupons.unCanUseCoupons" :key="couponId">
            <block v-if="nftCouponSts == 1 && update">
              <view class="coupon-item">
                <view class="left" style="background: linear-gradient(to right,#8c8c8c,#5f5f5f)!important;">
                  <view class="num">￥<text class="coupon-price">{{item.amount}}</text></view>
                  <view class="coupon-condition">
                    全场通用
                  </view>
                </view>
                <view class="right">
                  <view class="c-des">
                    <text class="c-type">商品</text>全场通用
                  </view>
                  <view class="c-date">
                    <view class="c-data-info">
                      {{ item.createTime }}
                    </view>
                  </view>
                </view>
              </view>
            </block>
          </block>
           -->
          <view class="botm-empty" />
        </view>
        <view v-if="nftCouponSts==0" class="coupon-ok">
          <text @tap="choosedNftCoupon">确定</text>
        </view>
      </view>
    </view>

    <!-- 积分输入框弹窗 -->
    <view class="popup-hide" :hidden="!showScorePop">
      <view class="popup-box score-pop">
        <view class="score-pop-con">
          <view class="score-pop-tit">
            <text>{{ i18n.modifyDeductiblePoints }}</text>
            <text class="close" @tap="closePopupHide" />
          </view>
          <view class="score-pop-item">
            <input class="score-int" type="number" placeholder-class="score-placeholder" :value="userUseScore" :placeholder="i18n.enterPoints" maxlength="8" @input="handleScoreInput" @click="hideTabbar" @focus="hideTabbar" @blur="showTabbar">
            <text class="usable-tips">{{ orderScorePlaceHolder }}</text>
            <view v-if="shopUseScore > 100" class="usable-tips">({{ i18n.multipleOf10 }})</view>
          </view>
          <view class="score-pop-item">
            <text class="confirm-btn" @tap="confirmScore">{{ i18n.confirm }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 选择配送方式弹窗 -->
    <view class="popup-hide" :hidden="!showDistributionPop">
      <view class="popup-box height-auto">
        <view class="con-tit">
          <view class="close" @tap="closePopup" />
          <view class="tit-text">{{ i18n.selectDeliveryMethod }}</view>
        </view>
        <view class="pop-con">
          <radio-group @change="disRadioChange">
            <label class="distribution-item">
              <view class="text">{{ i18n.ordinaryExpress }}</view>
              <radio color="#eb2444" class="check" value="1" :checked="dvyType==1" />
            </label>
            <label class="distribution-item">
              <view class="text">{{ i18n.sameDelivery }}</view>
              <radio color="#eb2444" class="check" value="4" :checked="dvyType==4" />
            </label>
          </radio-group>

        </view>
      </view>
    </view>

    <!-- 可用地址弹窗 -->
    <view class="popup-hide" :hidden="!showAddressListPop">
      <view class="popup-box address-list">
        <view class="con-tit">
          <view class="close" @tap="closePopup" />
          <view class="tit-text">{{ i18n.optionalAddress }}</view>
        </view>
        <view class="address-box">
          <radio-group v-for="(item, index) in addressList" :key="index" @change="addrRadioChange">
            <view class="item" @tap="selectAddr(item)">
              <view class="text-box">
                <view class="address"><text v-if="item.commonAddr == 1" class="default-address">{{ i18n.default }}</text>{{ item.province }}{{ item.city }}{{ item.area }}{{ item.addr }}</view>
                <view class="user">{{ item.receiver }} {{ item.mobile }}</view>
              </view>
              <radio color="#eb2444" class="check" :value="String(item.addrId)" :checked="addrId == item.addrId" />
            </view>
          </radio-group>
        </view>
      </view>
    </view>

    <!-- 历史提货人弹窗 -->
    <view class="popup-hide" :hidden="!showRaisingUserList">
      <view class="popup-box address-list history-user">
        <view class="con-tit">
          <view class="close" @tap="closePopup" />
          <view class="tit-text">{{ i18n.historicalPickPerson }}</view>
        </view>
        <view v-if="!stationUserInfo||stationUserInfo.length == 0" class="noData">{{ i18n.noData }}</view>
        <view v-if="stationUserInfo && stationUserInfo.length > 0" class="address-box">
          <radio-group v-for="(item,index) in stationUserInfo" :key="index" @change="stationRadioChange">
            <view class="item">
              <view class="text-box">
                <view class="address history-picker-user">
                  <view class="gray">{{ i18n.pickUpPerson }}：</view>
                  <view>{{ item.stationUserName }}</view>
                </view>
                <view class="address history-picker-user">
                  <view class="gray">{{ i18n.phoneNumber }}：</view>
                  <view>{{ item.stationUserMobile }}</view>
                </view>
              </view>
              <radio color="#FF6D13" class="check" :value="String(index)" :checked="stationIdx == index" @tap="getStationItem(item)" />
            </view>
          </radio-group>
        </view>
      </view>
    </view>

    <!-- 选择提货时间弹窗 -->
    <view class="popup-hide" :hidden="!showRaisingTimePop">
      <view class="popup-box raising-time">
        <view class="con-tit">
          <view class="tit-text">{{ i18n.choosePickUpTime }}</view>
          <view class="close" @tap="closePopup" />
        </view>
        <view class="time-box">
          <view v-if="selStationItem && timeParams" class="day-box">
            <view v-for="(item,dateIdx) in timeParams" :key="dateIdx" :class="['item', dateIndex==dateIdx?'active':'']" @tap="changeData(item,dateIdx)">{{ item.dateTime }}</view>
          </view>
          <block v-if="timeParams[dateIndex]">
            <view v-if="timeParams[dateIndex].hourTimes" class="hour-box">
              <radio-group v-for="(timeItem,timeIdx) in timeParams[dateIndex].hourTimes" :key="timeIdx">
                <view class="item" @tap="changeTime(timeItem,timeIdx)">
                  <view :class="['number', timeIndex==timeIdx?'red-word':'']">{{ timeItem }}</view>
                  <radio color="#FF6D13" v-if="timeIndex==timeIdx" class="check" :checked="timeIndex==timeIdx" :value="String(timeIdx)" />
                </view>
              </radio-group>
            </view>
          </block>
        </view>
      </view>
    </view>
    <invoiceEdit v-if="isShowInvoicePopup" :invoice-data-from="invoiceDataFrom" :shop-id="invoiceShopId" :invoice-id="invoiceId" @closePopup="closePopup" @getInvoiceData="getInvoiceData" />
  </view>
</template>

<script module="wxs" lang="wxs" src="../../wxs/number.wxs">
</script>

<script>
// pages/submit-order/submit-order.js
var http = require("../../utils/http.js");
var util = require("../../utils/util.js");
var index = [18, 0, 0];
var t = 0;
var show = false;
var moveY = 200;
import coupon from "../../components/order-coupon/index.vue";
import invoiceEdit from '../../components/invoice-edit/index'

export default {
  data () {
    return {
      canChooseSameCity: true,
      popupShow: false,
      nftPopupShow: false,//兑换卡弹出框
      couponSts: 1,
      nftCouponSts: 0,//兑换卡弹出框默认显示第一个tab
      canUseNftCount: 0,//可以使用的兑换卡数
      couponList: [],
      // 订单入口 0购物车 1立即购买
      orderEntry: "0",
      userAddr: null,
      orderItems: [],
      coupon: {
        totalLength: 0,
        canUseCoupons: [],
        noCanUseCoupons: []
      },
      nftCoupon: {
        totalLength: 0,
        unUseCount: 0,
        useCount: 0
      },
      actualTotal: 0,
      total: 0,
      totalCount: 0,
      transfee: 0,
      reduceAmount: 0,
      remark: "",
      couponIds: [],
      userNftCouponIds: [],//选中的兑换卡
      userChangeNftCoupon: 0,
      userChangeCoupon: 0,
      // 用户有没有对优惠券进行改变
      orderReduce: 0,
      choose: true,
      totalScoreAmount: 0,
      //积分抵扣金额
      totalUsableScore: 0,
      //整个订单可以使用的积分数
      isScorePay: 0,
      //用户是否选择积分抵现(0不使用 1使用 默认不使用)
      isChecked: false,
      //是否选择会员积分抵现
      isProhibit: false,
      //（积分抵现）checkbox是否禁止
      totalLevelAmount: 0,
      //等级抵扣金额
      freeTransfee: 0, //用户等级免运费金额
      coupons: {},
      nftCoupons: {},
      shopReduce: "",
      scorePrice: "",
      shopCartItemDiscounts: {},
      totalTransfee: 0, //运费
      update: false,
      couponReduce: 0, // 优惠券减免金额
      userUseScore: '', // 用于抵扣的金额数量
      scorePlaceholder: '', // 积分抵扣的占位符
      maxUsableScore: "", // 最大可用积分
      showScorePop: false, // 积分输入弹窗显隐
      accountCanUseScore: 0, // 用户当前可用积分
      shopUseScore: '', // 积分抵现比例

      isEditAddr: false, // 编辑地址
      showDistributionPop: false, // 选择物流方式弹窗
      addressList: [], // 地址列表
      showAddressListPop: false, // 可用地址弹窗
      isDistribution: true, // 配送方式tab状态
      showRaisingUserList: false, //选择历史提货人弹窗
      showRaisingTimePop: false, //选择提货时间弹窗

      dvyType: 1, // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
      filterShopItems: [], // 过滤掉的商品项

      value: [0, 0, 0],
      provArray: [],
      cityArray: [],
      areaArray: [],
      province: "",
      city: "",
      area: "",
      provinceId: 0,
      cityId: 0,
      areaId: 0,
      receiver: "",
      mobile: "",
      addr: "",
      addrId: 0,
      animation: "",
      show: "",
      region: "",

      stationUserName: '', // 提货人
      stationUserMobile: '', // 提货人手机号
      stationUserInfo: [], //历史提货人
      stationIdx: null, // 历史提货人选中index
      selStationItem: {}, // 选中的自提点数据
      timeParams: [],
      dateIndex: 0, // 日期下标
      timeIndex: null, // 时间下标
      timeContent: '', // 选中的时间
      dateContent: '', // 选中的日期
      selectDistributionWay: true, // 选择订单发货方式
      orderScorePlaceHolder: '', // 积分弹窗输入框订单可使用积分提示占位符
      disabled: false, // 是否禁止输入框输入
      selStation: '', // 是否选择自提点
      errorTips: 0, //错误提示
      // 判断悬浮框是否显示,当手机软键盘弹出,浮框隐藏
      tabbar: true,
      // 获取屏幕高度
      windowHeight: '',
      boolenRes: 1,  //1地址确认状态  //0地址未确认状态
      curLang: uni.getStorageSync('lang'),
      key: 'L4DBZ-VSSKJ-GCDFX-KGBVR-KHZ2J-RNF2Q',
      isMap: false,
      invoiceId: '', // 发票id
      invoiceShopId: '',
      invoiceDataFrom: {},
      isShowInvoicePopup: false,
      // 是否预售商品
      preSellStatus: 0,
      startDeliveryFee: 0,
    };
  },

  components: {
    coupon,
    invoiceEdit
  },
  props: {},

  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    this.setData({
      orderEntry: options.orderEntry
    });
    if (options.dvyType) {
      this.dvyType = options.dvyType
    }
    if (this.dvyType == 1 || this.dvyType == 4) { // 同城 || 邮寄
      this.isDistribution = true
    } else if (this.dvyType == 2) { // 自提
      this.isDistribution = false
    }

    if (this.dvyType == 2) {
      const info = uni.getStorageSync('selectedPickupinfors') || {}
      if (info) {
        this.stationUserName = info.stationUserName
        this.stationUserMobile = info.stationUserMobile
        this.stationIdx = info.stationIdx
      }
      // 清除选中的提货人信息
      uni.removeStorageSync('selectedPickupinfors')
    } else {
      // 清除选中的提货人信息
      uni.removeStorageSync('selectedPickupinfors')
    }
    this.setData({
      provArray: this.provArray.unshift({})
    })
    // this.initCityData(this.provinceId, this.cityId, this.areaId)
    this.loadAddressList() // 地址列表
  },

  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    });
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      // show: show
    });
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // 设置头部导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.submitOrders
    })
    const selStationItem = uni.getStorageSync('selStationItem')
    if (selStationItem) {
      this.selStationItem = selStationItem
      this.timeParams = selStationItem.timeParams
    }
    uni.removeStorageSync('selStationItem')
    // 获取当前可用积分
    this.getUserLevelInfo()
    // 数量兑换卡
    this.getNftCoupon()
    // 获取兑换卡列表
    this.getNftCouponList(0)
    this.getNftCouponList(1)
    //加载订单数据
    this.loadOrderData()
  },

  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () { },

  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () { },

  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () { },

  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () { },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function () { },
  methods: {
    /**
    * 腾讯地图以及微信小程序详细地址请求
    */
    selMap () {
      // #ifdef H5
      this.isMap = true
      this.tabbar = false
      let that = this
      window.addEventListener('message', function (event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        var loc = event.data
        if (loc && loc.module === 'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          that.addr = loc.poiaddress
          that.lat = loc.latlng.lat
          that.lng = loc.latlng.lng
          that.userAddr.lat = loc.latlng.lat
          that.userAddr.lng = loc.latlng.lng
          that.isMap = false
          that.tabbar = true
          util.area(loc.poiaddress, loc.poiname).then(res => {
            if (!res) return
            const addrReplacrstr = res[0].name + res[1].name + res[2].name
            that.addr = that.addr.replace(addrReplacrstr, '') || loc.poiname
            that.setData({
              value: [res[0].index, res[1].index, res[2].index],
              province: res[0].name,
              city: res[1].name,
              area: res[2].name,
              provinceId: res[0].areaId,
              cityId: res[1].areaId,
              areaId: res[2].areaId,
              provArray: res[3],
              cityArray: res[4],
              areaArray: res[5]
            })
            index = that.value
          })
          // 使上面的地区选择栏跟着改变
          // let provinceIndex = loc.poiaddress.indexOf('省')
          // if(loc.poiaddress.slice(0,(provinceIndex)+1) !== ''){
          // 	that.province = loc.poiaddress.slice(0,(provinceIndex)+1)
          // }

          // let cityIndex = loc.poiaddress.indexOf('市')
          // if(loc.poiaddress.slice(provinceIndex+1,cityIndex+1) !== ''){
          // 	that.city = loc.poiaddress.slice(provinceIndex+1,cityIndex+1)
          // }

          // let areaIndex = loc.poiaddress.indexOf('区')
          // if(loc.poiaddress.slice(0,(provinceIndex)+1) !== ''){
          // 	that.area = loc.poiaddress.slice(cityIndex+1,areaIndex+1)
          // }

        }
      }, false)
      // #endif

      // #ifdef MP-WEIXIN
      let that = this
      uni.chooseLocation({
        success: function (res) {
          that.setMapData(res);
        },
        fail: function (failMsg) {
          uni.getSetting({
            success (res) {
              if (!res.authSetting['scope.userLocation']) {
                console.log("f1");
                uni.authorize({
                  scope: 'scope.userLocation',
                  success () {
                    uni.chooseLocation({
                      success: function (res) {
                        that.setMapData(res);
                        // console.log(res)
                      }
                    })
                  },
                  fail () {
                    uni.showToast({
                      title: that.i18n.authorityTips,
                      icon: 'none'
                    });
                  }
                });
              }
            }
          });
        }
      });
      // #endif

      // #ifdef APP-PLUS
      let that = this
      uni.chooseLocation({
        success: function (res1) {
          uni.getLocation({
            type: 'wgs84',
            geocode: true,
            success: function (res) {
              util.area(res1.address, res1.name).then(res => {
                if (!res) return
                that.setData({
                  value: [res[0].index, res[1].index, res[2].index],
                  province: res[0].name,
                  city: res[1].name,
                  area: res[2].name,
                  provinceId: res[0].areaId,
                  cityId: res[1].areaId,
                  areaId: res[2].areaId,
                  provArray: res[3],
                  cityArray: res[4],
                  areaArray: res[5]
                })
                index = that.value
              })
              that.setData({
                lat: res1.latitude,
                lng: res1.longitude,
                addr: res1.address,
              });
            }
          });
        }
      });
      // #endif
    },

    isMapReturn () {
      this.isMap = false;
      this.tabbar = true;
    },

    // 提交订单浮框的显隐
    showTabbar () {
      if (this.disabled == false) {
        this.tabbar = true
      }
    },
    hideTabbar () {
      if (this.disabled == false) {
        this.tabbar = true
      }
    },
    // 切换配送方式
    changeDistribution: function (sts) { // 邮寄或同城
      if (sts == 0) {
        this.isDistribution = true
        this.dvyType = 1
      } else if (sts == 1) { // 自提
        this.isDistribution = false
        this.dvyType = 2
      }
      this.loadOrderData()
    },

    // 选择配送方式
    disRadioChange (e) {
      // console.log(e)
      this.dvyType = e.detail.value
      this.loadOrderData()
      this.showDistributionPop = false
    },

    // 选择地址
    addrRadioChange (e) {
      // console.log(e)
      this.addrId = e.detail.value
      this.showAddressListPop = false
      this.isEditAddr = false
      this.getAddrDet()
    },
    selectAddr: function (item) {
      // console.log(item)
      this.addrId = item.addrId
      this.showAddressListPop = false
      this.isEditAddr = false
      this.getAddrDet()
      this.setData({
        boolenRes: 1
      })
    },

    // 选择历史提货人
    stationRadioChange (e) {
      // console.log(e)
      this.stationIdx = e.detail.value
      this.showRaisingUserList = false
      this.raisingUserList()
    },
    getStationItem: function (item) {
      this.stationUserName = item.stationUserName
      this.stationUserMobile = item.stationUserMobile
      this.showRaisingUserList = false
    },

    // 加载地址列表
    loadAddressList: function () {
      var ths = this;
      var params = {
        url: "/p/address/list",
        method: "GET",
        data: {},
        callBack: function (res) {
          ths.setData({
            addressList: res
          });
        }
      };
      http.request(params);
    },
    //根据地址id请求地址详情
    getAddrDet: function () {
      var params = {
        url: "/p/address/addrInfo/" + this.addrId,
        method: "GET",
        data: {},
        callBack: (res) => {
          this.userAddr = res
          this.loadOrderData()
        }
      };
      http.request(params);
    },

    //  获取会员积分详情
    getUserLevelInfo () {
      var params = {
        url: '/p/score/scoreInfo',
        method: 'GET',
        dontTrunLogin: true,
        data: {},
        callBack: res => {
          this.setData({
            accountCanUseScore: res.score
          });
        }
      };
      http.request(params);
    },

    // 会员积分抵现选择
    useMemberPoints: function () {
      this.isChecked = !this.isChecked;
      // console.log(this.isChecked)
      if (this.maxUsableScore > 0) {
        //totalUsableScore整个订单可以使用的积分数
        this.setData({
          isScorePay: this.isChecked ? 1 : 0,
          userUseScore: this.isChecked ? this.userUseScore : ''
        });
        // console.log(this.isScorePay)
        // console.log('userUseScore:', this.userUseScore)
        this.loadOrderData();
      }
    },

    // 积分抵扣输入框
    handleScoreInput (e) {
      if (e.detail.value.indexOf('-') >= 0) {
        e.detail.value = e.detail.value.replace('-', '')
      }
      this.userUseScore = e.detail.value.replace(/[^\d]/g, '')
    },

    // 兑换卡数量
    getNftCoupon: function () {
      var ths = this;
      var params = {
        url: "/p/userNftCoupon/getStatusCount",
        method: "GET",
        callBack: function (res) {
          ths.nftCoupon.unUseCount = res.unUseCount;// 未使用
          ths.nftCoupon.useCount = res.useCount;// 已使用
        },
      };
      http.request(params);
    },
    // 兑换卡列表
    getNftCouponList: function (str) {
      var ths = this;
      var params = {
        url: "/p/userNftCoupon/getList",
        method: "GET",
        data: {
          current: 1,
          size: 100,
          status: str
        },
        callBack: function (res) {
          if (str == 0) {
            ths.nftCoupons.canUseCoupons = res.records
          }
          if (str == 1) {
            ths.nftCoupons.unCanUseCoupons = res.records
          }
        },
      };
      http.request(params);
    },
    // 加载订单数据
    loadOrderData: function () {
      var addrId = 0;

      if (this.userAddr != null) {
        addrId = this.userAddr.addrId;
      }
      var params = {
        url: "/p/order/confirm",
        method: "POST",
        data: {
          addrId: addrId,
          orderItem: this.orderEntry === "1" ? JSON.parse(wx.getStorageSync("orderItem")) : undefined,
          basketIds: this.orderEntry === "0" ? JSON.parse(wx.getStorageSync("basketIds")) : undefined,
          couponIds: this.couponIds,
          userNftCouponIds: this.userNftCouponIds,
          userChangeCoupon: this.userChangeCoupon,
          isScorePay: this.isScorePay,
          userUseScore: parseInt(this.userUseScore),
          dvyType: this.dvyType, // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
        },
        callBack: res => {
          let orderItems = [];

          if (res.shopCartOrders && res.shopCartOrders[0]) {
            res.shopCartOrders[0].shopCartItemDiscounts.forEach(itemDiscount => {
              orderItems = orderItems.concat(itemDiscount.shopCartItems);
            });

            if (res.shopCartOrders[0].coupons) {
              let canUseCoupons = [];
              let unCanUseCoupons = [];
              res.shopCartOrders[0].coupons.forEach(coupon => {
                if (coupon.canUse) {
                  canUseCoupons.push(coupon);
                } else {
                  unCanUseCoupons.push(coupon);
                }
              });
              canUseCoupons.forEach(item => {
                if (item.choose) {
                  this.couponIds.push(item.couponId)
                }
              })
              this.setData({
                coupons: {
                  totalLength: res.shopCartOrders[0].coupons.length,
                  canUseCoupons: canUseCoupons,
                  unCanUseCoupons: unCanUseCoupons
                }
              });
            }

          };

          var scorePlaceholder = this.i18n.use + ' ' + res.totalUsableScore + ' ' + this.i18n.pointsDeduction + ' ' +
            res.totalScoreAmount + ' ' + this.i18n.yuan;
          var orderScorePlaceHolder = this.i18n.accountSurplus + this.accountCanUseScore + this.i18n.accountSurplus2 + res.maxUsableScore;
          console.log('==========>>>>>>>>>>>>>>>>>>>>>>>>>>>')
          console.log(res)
          console.log(res.shopCartOrders)
          console.log(res.shopCartOrders[0])
          console.log(res.shopCartOrders[0].startDeliveryFee)
          console.log('==========>>>>>>>>>>>>>>>>>>>>>>>>>>>')
          this.setData({
            canChooseSameCity: Boolean(res.shopCityStatus), // 订单是否支持同城配送
            orderItems: orderItems,
            actualTotal: res.actualTotal,
            total: res.total,
            totalCount: res.totalCount,
            userAddr: res.userAddr,
            shopReduce: res.shopCartOrders[0] ? res.shopCartOrders[0].shopReduce : 0,
            totalLevelAmount: res.totalLevelAmount,
            freeTransfee: res.freeTransfee,
            isScorePay: res.isScorePay,
            totalScoreAmount: res.totalScoreAmount,
            totalUsableScore: res.totalUsableScore,
            scorePrice: res.scorePrice,
            shopCartItemDiscounts: res.shopCartOrders[0] ? res.shopCartOrders[0].shopCartItemDiscounts : [],
            couponReduce: res.shopCartOrders[0] ? res.shopCartOrders[0].couponReduce : 0, // 优惠券减免金额
            totalTransfee: res.totalTransfee, //运费
            maxUsableScore: res.maxUsableScore,
            scorePlaceholder: scorePlaceholder,
            orderScorePlaceHolder: orderScorePlaceHolder,
            shopUseScore: res.shopUseScore, // 积分抵现比例;
            filterShopItems: res.filterShopItems, // 过滤掉的商品项
            preSellStatus: res.shopCartOrders[0] ? res.shopCartOrders[0].shopCartItemDiscounts[0].shopCartItems[0].preSellStatus : false, // 是否预售商品
            startDeliveryFee: res.shopCartOrders[0].startDeliveryFee,
            transfee: res.shopCartOrders[0].transfee
          })
          console.log('------------------------')
          console.log(this.startDeliveryFee)
          // console.log(1,this.shopCartItemDiscounts,res);
          this.getStationUserInfo() // 历史提货人
          this.disabledInput() // 是否禁止提货人输入框输入
        },
        errCallBack: err => {
          uni.hideLoading();
          uni.showModal({
            title: this.i18n.tips,
            content: err.msg,
            showCancel: false,//是否显示取消按钮
            confirmText: this.i18n.confirm,
            success: (modalSuccess) => {
              if (modalSuccess.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          })
        }
      };
      http.request(params);
    },

    // 提交订单
    toPay: function () {
      if (this.dvyType == 1 || this.dvyType == 4) {
        if (this.isEditAddr) {
          uni.showToast({
            title: this.i18n.saveAndUseTips,
            icon: 'none'
          })
          return
        }
        if (!this.userAddr) {
          uni.showToast({
            title: this.i18n.pleaseSelectSddress,
            icon: "none"
          });
        }
        if (!this.shopCartItemDiscounts.length) {
          var title = this.dvyType == 1 ? this.i18n.expressDelivery : this.dvyType == 4 ? this.i18n.sameDelivery : ''
          uni.showToast({
            title: this.i18n.productNotSupported + title,
            icon: "none"
          });
          return;
        }
        if (this.dvyType == 4 && (!this.userAddr.lat || this.userAddr.lat == 0 || !this.userAddr.lng || this.userAddr.lng ==
          0)) {
          uni.showModal({
            title: this.i18n.tips,
            content: this.i18n.cityAddressPrompt,
            showCancel: false,
            success: res => {
              uni.navigateTo({
                url: '/pages/edit-address/edit-address?addrId=' + this.userAddr.addrId
              })
            }
          })
          return;
        }
      } else if (this.dvyType == 2) {
        if (!this.shopCartItemDiscounts.length) {
          uni.showToast({
            title: this.i18n.productNotSupportedStop,
            icon: "none"
          });
          return;
        }
        if (!this.selStationItem.province) {
          uni.showToast({
            title: this.i18n.selectPickPoint,
            icon: "none"
          });
          return;
        }
        if (/^\s+$/g.test(this.stationUserName)) {
          wx.showToast({
            title: this.i18n.inputAllSpace,
            icon: "none"
          });
          return;
        }
        if (!this.stationUserName || !this.stationUserMobile) {
          uni.showToast({
            title: this.i18n.fillDeliveryPersonInformation,
            icon: "none"
          });
          return;
        }
        if (!util.checkPhoneNumber(this.stationUserMobile)) {
          uni.showToast({
            title: this.i18n.enterCorrectPhone,
            icon: "none"
          });
          return;
        }
        if (!this.dateContent || !this.timeContent) {
          uni.showToast({
            title: this.i18n.selectPickUpTime,
            icon: "none"
          });
          return;
        }
      }

      // 点击地址判断
      if ((this.isEditAddr || this.addressList[0] === undefined) && this.dvyType == 1) {
        uni.showToast({
          title: this.i18n.pleaseCompleteTheInformation,
          icon: 'none'
        })
        return
      }
      this.submitOrder();
    },
    submitOrder: function () {
      var isPurePoints = this.actualTotal > 0 ? '' : 1 // 是否纯积分: 1是
      if (this.isScorePay == 1 && this.userUseScore <= 0) {
        uni.showToast({
          title: this.i18n.enterPoints,
          icon: 'none'
        })
        return
      }
      var shopCartItemDiscounts = this.shopCartItemDiscounts;
      var orderSelfStationDto = {
        stationId: this.selStationItem.stationId,
        stationTime: this.dateContent + ' ' + this.timeContent,
        stationUserMobile: this.stationUserMobile,
        stationUserName: this.stationUserName
      }
      let orderInvoiceList = [] // invoiceDataFrom
      if (this.invoiceDataFrom && this.invoiceDataFrom.invoiceType === 1) {
        orderInvoiceList.push(this.invoiceDataFrom)
      }
      if (orderInvoiceList.length === 0) {
        orderInvoiceList = null
      }
      // console.log(orderInvoiceList)
      var params = {
        url: "/p/order/submit",
        method: "POST",
        data: {
          orderShopParam: [{
            remarks: !this.remark.trim() ? null : this.remark,
            shopId: 1
          }],
          coupons: this.coupons,
          isScorePay: this.isScorePay,
          orderSelfStationDto: orderSelfStationDto,
          orderInvoiceList: orderInvoiceList
        },
        callBack: res => {
          this.$Router.replace({
            path: '/pages/pay-way/pay-way',
            query: { orderNumbers: res.orderNumbers, dvyType: this.dvyType, isPurePoints: isPurePoints },
          });
        },
        errCallBack: res => {
          uni.showModal({
            title: this.i18n.tips,
            content: res.msg,
            showCancel: false,
            confirmText: this.i18n.confirm,
            confirmColor: '#FF6D13',
            success: (errModalRes) => {
              if (errModalRes.confirm) {
                uni.navigateBack({
                  delta: 1,
                })
              }
            }
          })
        }
      };
      http.request(params);
    },

    changeCouponSts: function (e) {
      this.setData({
        couponSts: e.currentTarget.dataset.sts,
        update: true
      });
    },
    changeNftCouponSts: function (e) {
      this.setData({
        nftCouponSts: e.currentTarget.dataset.sts,
        update: true
      });
    },
    showCouponPopup: function () {
      this.setData({
        popupShow: true
      });
      this.coupons.canUseCoupons.forEach(item => {
        if (this.couponIds.indexOf(item.couponId) !== -1) {
          item.choose = true
        } else {
          item.choose = false
        }
      })
    },
    showNftCouponPopup: function () {
      this.setData({
        nftPopupShow: true
      });
      this.nftCoupons.canUseCoupons.forEach(item => {
        if (this.userNftCouponIds.indexOf(item.couponId) !== -1) {
          item.choose = true
        } else {
          item.choose = false
        }
      })
    },
    closePopup: function () {
      this.setData({
        nftPopupShow: false,
        popupShow: false,
        showScorePop: false,
        showDistributionPop: false,
        showAddressListPop: false,
        showRaisingUserList: false,
        showRaisingTimePop: false,
        isShowInvoicePopup: false
      });
    },

    closePopupHide () {
      this.userUseScore = ''
      this.setData({
        popupShow: false,
        showScorePop: false,
        showDistributionPop: false,
        showAddressListPop: false,
        showRaisingUserList: false,
        showRaisingTimePop: false,
        isShowInvoicePopup: false
      });
    },

    /**
    * 去地址页面
    */
    toAddrListPage: function () {
      // uni.navigateTo({
      // 	url: '/pages/delivery-address/delivery-address?order=0'
      // });
      this.isEditAddr = true
      this.setData({
        boolenRes: 0,
        addrId: ''
      })
    },
    // 发票信息弹窗
    showInvoicePopup (shopId, invoiceDataFrom) {
      if (invoiceDataFrom) {
        this.invoiceDataFrom = invoiceDataFrom
      }
      this.invoiceShopId = shopId
      this.isShowInvoicePopup = true
    },
    getInvoiceData (data) {
      // invoiceDataFrom
      this.invoiceDataFrom = data
      // console.log(data)
    },

    /**
    * 确定选择好的优惠券
    */
    choosedCoupon: function () {
      var couponIds = [];
      var canUseCoupons = this.coupons.canUseCoupons;

      for (var canUseCouponIndex in canUseCoupons) {
        if (canUseCoupons[canUseCouponIndex].choose) {
          // 找到所有被选中的优惠券
          couponIds.push(canUseCoupons[canUseCouponIndex].couponId);
        }
      }

      this.setData({
        couponIds: couponIds
      });
      this.loadOrderData();
      this.setData({
        popupShow: false
      });
    },

    /**
    * 确定选择好的兑换卡
    */
    choosedNftCoupon: function () {
      var userNftCouponIds = [];
      var canUseCoupons = this.nftCoupons.canUseCoupons;
      for (var canUseCouponIndex in canUseCoupons) {
        if (canUseCoupons[canUseCouponIndex].choose) {
          // 找到所有被选中的优惠券
          userNftCouponIds.push(canUseCoupons[canUseCouponIndex].couponId);
        }
      }

      this.setData({
        userNftCouponIds: userNftCouponIds
      });

      this.loadOrderData();
      this.setData({
        nftPopupShow: false
      });
    },

    /**-
    * 选择兑换卡
    */
    checkNftCoupon: function (e) {
      // 兑换卡单选操作
      var nftCoupons = this.nftCoupons;
      var canUseCoupons = this.nftCoupons.canUseCoupons;
      for (var canUseCouponIndex in canUseCoupons) {
        if (e.target.dataset.couponid == canUseCoupons[canUseCouponIndex].couponId) {
          // 选中了变成没有选中
          if (canUseCoupons[canUseCouponIndex].choose) {
            canUseCoupons[canUseCouponIndex].choose = false;
          } else {
            canUseCoupons[canUseCouponIndex].choose = true;
            // 没有选中则变成选中，其他被选中的变成没有选中
            // for (var newCanUseCoupons in canUseCoupons) {
            // 	canUseCoupons[newCanUseCoupons].choose = canUseCoupons[canUseCouponIndex].couponId === canUseCoupons[newCanUseCoupons].couponId;
            // }
          }
          this.setData({
            nftCoupons: nftCoupons,
            userChangeNftCoupon: 1
          });
          break;
        }
      }
    },

    /**-
    * 优惠券子组件发过来
    */
    checkCoupon: function (e) {
      // 优惠券单选操作
      var coupons = this.coupons;
      var canUseCoupons = coupons.canUseCoupons;
      for (var canUseCouponIndex in canUseCoupons) {
        if (e.couponId == canUseCoupons[canUseCouponIndex].couponId) {
          // 选中了变成没有选中
          if (canUseCoupons[canUseCouponIndex].choose) {
            canUseCoupons[canUseCouponIndex].choose = false;
          } else {
            // 没有选中则变成选中，其他被选中的变成没有选中
            for (var newCanUseCoupons in canUseCoupons) {
              canUseCoupons[newCanUseCoupons].choose = canUseCoupons[canUseCouponIndex].couponId === canUseCoupons[newCanUseCoupons].couponId;
            }
          }

          this.setData({
            coupons: coupons,
            userChangeCoupon: 1
          });
          break;
        }
      }
    },

    // 输入备注
    onRemarkIpt: function (e) {
      this.setData({
        remark: e.detail.value
      });
    },

    /**
     * 积分输入弹窗显示
     */
    handleScorePop () {
      this.setData({
        showScorePop: true
      });
    },

    /**
     * 积分抵扣输入框
     */
    // handleScoreInput(e) {
    // 	console.log(e)
    // 	var maxScore = 0 // 最大可使用积分
    // 	if (this.maxUsableScore > this.accountCanUseScore) {
    // 		//本单可使用积分 > 用户当前可用积分时
    // 		maxScore = this.accountCanUseScore
    // 	} else {
    // 		maxScore = this.maxUsableScore
    // 	}
    // 	this.userUseScore = e.detail.value > 0 ? e.detail.value > maxScore ? maxScore : e.detail.value : ''
    // 	if (e.detail.value > maxScore) {
    // 		this.userUseScore = maxScore
    // 	}
    // },

    /**
     * 修改积分确定弹窗
     */
    confirmScore () {
      if (this.userUseScore > this.maxUsableScore || this.userUseScore > this.accountCanUseScore) {
        uni.showToast({
          title: this.i18n.exceedPointsTips + this.maxUsableScore + this.i18n.integral,
          icon: 'none'
        });
      } else {
        if (this.shopUseScore > 100) {
          this.userUseScore = this.userUseScore - (this.userUseScore % 10)
        }
        // console.log(this.shopUseScore,'2222');
        this.loadOrderData();
        this.closePopup();
      }
    },

    /**
     * 积分输入弹窗显示
     */
    // handleScorePop() {
    // 	var maxScore = 0
    // 	if (this.maxUsableScore > this.accountScore) {
    // 		maxScore = this.accountScore
    // 	} else {
    // 		maxScore = this.maxUsableScore
    // 	}
    // 	this.userUseScore = this.userUseScore > maxScore ? maxScore : this.userUseScore
    // 	this.setData({
    // 		showScorePop: true
    // 	});
    // }

    /**
     * 物流选择弹窗显示
     */
    distributionPop () {
      this.setData({
        showDistributionPop: true
      });
    },

    /**
     * 可用地址弹窗显示
     */
    AddressListPop () {
      if (this.addressList.length) {
        this.setData({
          showAddressListPop: true
        });
      }
    },

    /**
     * 历史提货人弹窗显示
     */
    raisingUserList () {
      if (this.dvyType == 2 && !this.shopCartItemDiscounts.length) {
        uni.showToast({
          title: this.i18n.productNotSupportedStop,
          icon: 'none'
        })
        return
      }
      this.setData({
        showRaisingUserList: true
      });

    },

    /**
     * 选择提货时间弹窗显示
     */
    raisingTimePop () {
      if (!this.selStationItem.province) {
        uni.showToast({
          title: this.i18n.selectPickPoint,
          icon: 'none'
        })
      } else {

        this.setData({
          showRaisingTimePop: true,
        });

        let a = (this.timeParams[0].dateTime).split('-')
        this.dateContent = a[0] + '-' + a[1]
      }
    },

    /**
     * 选择自提点
     */
    goSelectStore () {
      // console.log(!this.shopCartItemDiscounts.length)
      if (!this.shopCartItemDiscounts.length) {
        uni.showToast({
          title: this.i18n.productNotSupportedStop,
          icon: "none"
        });
        return;
      }
      // 选择与重新选择自提点时时间
      this.setData({
        dateIndex: 0, // 日期下标
        timeIndex: null, // 时间下标
        timeContent: '', // 选中的时间
        dateContent: '', // 选中的日期
      })
      // 将已选择/已填写的历史提货人信息保存起来
      if (this.stationUserName || this.stationUserMobile || this.stationIdx) {
        const selectedPickupinfor = {
          stationUserName: this.stationUserName,
          stationUserMobile: this.stationUserMobile,
          stationIdx: this.stationIdx
        }
        uni.setStorageSync('selectedPickupinfors', selectedPickupinfor)
      }
      uni.navigateTo({
        url: '/pages/select-store/select-store?shopId=1' + '&orderEntry=' + this.orderEntry
      })
    },

    /**
     * 禁止输入提货人信息
     */
    disabledInput: function () {
      if (this.dvyType == 2 && !this.shopCartItemDiscounts.length) {
        this.disabled = true
      } else {
        this.disabled = false
      }
    },

    /**
     * 获取历史提货人列表
     */
    getStationUserInfo: function () {
      var params = {
        url: "/p/orderSelfStation/getStationUserInfo",
        method: "GET",
        data: {},
        callBack: (res) => {
          this.stationUserInfo = res
        }
      };
      http.request(params);
    },

    getConsigneeInt: function (e) {
      this.stationUserName = e.detail.value
    },

    getConMobileInt: function (e) {
      this.stationUserMobile = e.detail.value
    },

    /**
     * 改变预约自提日期选择
     */
    changeData: function (item, dateIdx) {
      this.dateIndex = dateIdx
      // console.log(this.dateIndex, this.timeParams[this.dateIndex].hourTimes)

      // 点击日期时默认选中第一个时间段
      this.timeIndex = 0; // 时间下标
      this.timeContent = this.timeParams[this.dateIndex].hourTimes[0]
      let a = (item.dateTime).split('-')

      this.dateContent = a[0] + '-' + a[1]
      // console.log(this.dateContent);
    },

    /**
     * 改变预约自提时间选择
     */
    changeTime: function (timeItem, timeIdx) {
      this.timeIndex = timeIdx
      // console.log(this.timeIndex)
      this.showRaisingTimePop = false
      this.timeContent = timeItem
      // console.log(timeItem)
      // console.log(this.timeContent)
    },

    /**
     * 获取全部省份
     */
    initCityData: function (provinceId, cityId, areaId) {
      var ths = this;
      var params = {
        url: "/p/area/listByPid",
        method: "GET",
        data: {
          pid: 0
        },
        callBack: function (res) {
          var data = res
          // data.unshift({})
          ths.setData({
            provArray: data
          });
          if (provinceId) {
            for (var index in data) {
              if (res[index].areaId == provinceId) {
                ths.setData({
                  value: [Number(index), ths.value[1], ths.value[2]]
                  // value: [0, 0, 0]
                });
              }
            }
          }
          ths.getCityArray(provinceId ? provinceId : res[0].areaId, cityId, areaId);
        }
      };
      http.request(params);
    },

    /**
     * 根据省份ID获取 城市数据
     */
    getCityArray: function (provinceId = '', cityId, areaId) {
      if (provinceId === '') {
        this.setData({
          cityArray: [],
          areaArray: []
        });
        return
      }
      var ths = this;
      var params = {
        url: "/p/area/listByPid",
        method: "GET",
        data: {
          pid: provinceId
        },
        callBack: function (res) {
          //console.log(res)
          ths.setData({
            cityArray: res
          });

          if (cityId) {
            for (var index in res) {
              if (res[index].areaId == cityId) {
                ths.setData({
                  value: [ths.value[0], Number(index), Number(ths.value[2])]
                  // value: [0, 0, 0]
                });
              }
            }
          }

          ths.getAreaArray(cityId ? cityId : res[0].areaId, areaId);
        }
      };
      http.request(params);
    },

    /**
     * 根据城市ID获取 区数据
     */
    getAreaArray: function (cityId = '', areaId) {
      var ths = this;
      if (cityId === '') {
        return
      }
      var params = {
        url: "/p/area/listByPid",
        method: "GET",
        data: {
          pid: cityId
        },
        callBack: function (res) {
          //console.log(res)
          ths.setData({
            areaArray: res
          });
          ths.setData({
            province: ths.provArray[ths.value[0]].areaName,
            city: ths.cityArray[ths.value[1]].areaName,
            area: ths.areaArray[ths.value[2]].areaName,
            provinceId: ths.provArray[ths.value[0]].areaId,
            cityId: ths.cityArray[ths.value[1]].areaId,
            areaId: ths.areaArray[ths.value[2]].areaId
          });
        }
      };
      http.request(params);
    },

    onReceiverInput: function (e) {
      this.setData({
        receiver: e.detail.value
      });
    },
    onMobileInput: function (e) {
      this.setData({
        mobile: e.detail.value
      });
    },
    onAddrInput: function (e) {
      this.setData({
        addr: e.detail.value
      });
    },

    /**
     * 保存地址
     */
    onSaveAddr: function () {
      var receiver = this.receiver;
      var mobile = this.mobile;
      var addr = this.addr;
      var reg = /^\s+$/g
      console.log('提交的经纬度：', this.lng, ',', this.lat)
      if (this.addressList.length == 10) {
        uni.showToast({
          title: this.i18n.newAddressesLimit,
          icon: "none",
          duration: 1500
        });
        return;
      }
      if (!receiver.trim()) {
        this.receiver = ''
        uni.showToast({
          title: this.i18n.consigneeTips,
          icon: "none"
        });
        return;
      }
      if (!mobile) {
        uni.showToast({
          title: this.i18n.enterMobileNumber,
          icon: "none"
        });
        return;
      }
      if (!util.checkPhoneNumber(mobile)) {
        uni.showToast({
          title: this.i18n.enterCorrectPhone,
          icon: "none"
        });
        return;
      }
      if (!this.province || !this.city || !this.area) {
        uni.showToast({
          title: this.i18n.selectProvinceCity,
          icon: "none"
        });
        return;
      }
      if (!addr.trim() || addr.length < 5) {
        uni.showToast({
          title: this.i18n.enterCorrectAddress,
          icon: "none"
        });
        return;
      }
      if (reg.test(addr)) {
        wx.showToast({
          title: this.i18n.inputAllSpace,
          icon: "none"
        });
        return;
      }
      if (this.dvyType == 4) {
        // 同城配送
        if (!this.lat || !this.lng || this.lat == '' || this.lng == '') {
          uni.showModal({
            title: this.i18n.tips,
            content: this.i18n.selectCoordinates,
            showCancel: false,
            success: res => {
              uni.navigateTo({
                url: '/pages/edit-address/edit-address?addrId=' + this.userAddr.addrId
              })
            }
          })
        }
      } var url = "/p/address/addAddr";
      var method = "POST";
      //添加或修改地址
      var params = {
        url: url,
        method: method,
        data: {
          receiver: this.receiver,
          mobile: this.mobile,
          addr: this.addr,
          province: this.province,
          provinceId: this.provinceId,
          city: this.city,
          cityId: this.cityId,
          areaId: this.areaId,
          area: this.area,
          userType: 0,
          // addrId: this.addrId,
          lat: this.lat, // 纬度
          lng: this.lng, // 经度
        },
        callBack: (res) => {
          this.loadAddressList()
          uni.showToast({
            title: this.i18n.savedSuccessfully,
            icon: 'none',
            duration: 1000
          })
          this.addr = ''
          this.receiver = ''
          this.mobile = ''
          this.isEditAddr = false
          if (this.addressList.length > 1) {
            setTimeout(() => {
              this.addrId = this.addressList[1].addrId
            }, 100);
          } else {
            setTimeout(() => {
              this.addrId = this.addressList[0].addrId
            }, 100);
          }

          this.setData({
            province: this.provArray[this.value[0]].areaName,
            city: this.cityArray[this.value[1]].areaName,
            area: this.areaArray[this.value[2]].areaName,
            provinceId: this.provArray[this.value[0]].areaId,
            cityId: this.cityArray[this.value[1]].areaId,
            areaId: this.areaArray[this.value[2]].areaId,
          });
          setTimeout(() => {
            this.getAddrDet()
          }, 100);
        }
      };
      http.request(params);
    },

    //滑动事件
    bindChange: function (e) {
      var val = e.detail.value; //判断滑动的是第几个column
      console.log(e)
      //若省份column做了滑动则定位到地级市和区县第一位

      if (index[0] != val[0]) {
        val[1] = 0;
        val[2] = 0; //更新数据
        console.log(this.provArray[val[0]])
        this.getCityArray(this.provArray[val[0]].areaId); //获取地级市数据
      } else {
        //若省份column未做滑动，地级市做了滑动则定位区县第一位
        if (index[1] != val[1]) {
          val[2] = 0; //更新数据
          this.getAreaArray(this.cityArray[val[1]].areaId); //获取区县数据
        } else { }
      }

      index = val;
      this.setData({
        value: [val[0], val[1], val[2]]
      });
      this.setData({
        province: this.provArray[this.value[0]].areaName,
        city: this.cityArray[this.value[1]].areaName,
        area: this.areaArray[this.value[2]].areaName,
        provinceId: this.provArray[this.value[0]].areaId,
        cityId: this.cityArray[this.value[1]].areaId,
        areaId: this.areaArray[this.value[2]].areaId
      });
    },

    //移动按钮点击事件
    translate: function (e) {
      if (t == 0) {
        console.log('t == 0')
        moveY = 0;
        show = false;
        t = 1;
      } else {
        console.log('else')
        moveY = 200;
        show = true;
        t = 0;
      }
      this.initCityData(this.provinceId, this.cityId, this.areaId)
      this.setData({
        show: true
      });
      this.animationEvents(this, moveY, show);
    },

    //隐藏弹窗浮层
    hiddenFloatView (e) {
      moveY = 200;
      show = true;
      t = 0;
      this.animationEvents(this, moveY, show);

      this.setData({
        province: this.provArray[this.value[0]].areaName,
        city: this.cityArray[this.value[0]].areaName,
        area: this.areaArray[this.value[0]].areaName,
        provinceId: this.provArray[this.value[0]].areaId,
        cityId: this.cityArray[this.value[0]].areaId,
        areaId: this.areaArray[this.value[0]].areaId
      });
      this.showTabbar()
    },

    //动画事件
    animationEvents: function (that, moveY, show) {
      that.animation = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 400,
        timingFunction: "ease",
        delay: 0
      });
      that.animation.translateY(moveY + 'vh').step();
      that.setData({
        animation: that.animation.export()
      });
    },

    // 空方法
    nono () {

    },
    setMapData (res) {
      this.lat = res.latitude; // 纬度
      this.lng = res.longitude; // 经度
      this.addr = res.address; // 详细地址
      this.name = res.name; // 详细地址

      console.log('腾讯/高德地图经纬度：', this.lng, '，', this.lat)
      util.area(res.address, res.name).then(res2 => {
        if (!res2) return
        this.setData({
          value: [res2[0].index, res2[1].index, res2[2].index],
          province: res2[0].name,
          city: res2[1].name,
          area: res2[2].name,
          provinceId: res2[0].areaId,
          cityId: res2[1].areaId,
          areaId: res2[2].areaId,
          provArray: res2[3],
          cityArray: res2[4],
          areaArray: res2[5]
        })
        index = this.value
      })
      this.qqMapTransBMap(this.lng, this.lat)
    },

    // 将腾讯/高德地图经纬度转换为百度地图经纬度
    qqMapTransBMap: function (lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta) + 0.0065;
      let lats = z * Math.sin(theta) + 0.006;

      this.lng = lngs
      this.lat = lats

      console.log('百度地图经纬度：', this.lng, '，', this.lat)
      return {
        lng: lngs,
        lat: lats
      }
    },
  }
}
</script>
<style scoped  lang='scss'>
@import "./submit-order.scss";
</style>
